package com.example.demo.manager;

import com.example.demo.domain.db.OrderInfo;
import com.example.demo.domain.solr.Orders;
import com.example.demo.manager.inf.CanalManager;
import com.example.demo.repository.OrdersUtil;
import com.example.demo.repository.SolrRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @Description
 * @Author <a href="hedong.wu@baozun.com">wuhedong</a>
 * @Date 2020/5/29 19:16
 **/

@Slf4j
@Component("order_info")
public class OrderInfoManage implements CanalManager<OrderInfo> {

    @Autowired
    SolrRepository solrRepository;

    @Override
    public boolean doOnDelete(OrderInfo orderInfo) {
        return doSolr(new OrderInfo(orderInfo.getOrderId()));
    }

    @Override
    public boolean doOnUpdate(OrderInfo beforeOrders, OrderInfo afterOrders) {
        return doSolr(afterOrders);

    }

    @Override
    public boolean doOnAdd(OrderInfo orderInfo) {
        return doSolr(orderInfo);
    }

    /**
     * 共同体
     */
    public boolean doSolr(OrderInfo orderInfo){
        Optional<Orders> byId = solrRepository.findById(orderInfo.getOrderId());
        if(!byId.isPresent()){
            return true;
        }
        Orders orders = byId.get();
        OrdersUtil.mergeOrdersWithorderinfo(orders,orderInfo);
        solrRepository.save(orders);
        return true;
    }

    @Override
    public Class<OrderInfo> getHandleClass() {
        return OrderInfo.class;
    }

}
